package com.core;

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class ColorBasedDetection {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        // 加载图像
        Mat image = Imgcodecs.imread("Z:\\Users\\adwszzy\\Desktop\\789.png");

        // 转换到HSV色彩空间
        Mat hsv = new Mat();
        Imgproc.cvtColor(image, hsv, Imgproc.COLOR_BGR2HSV);

        // 设定颜色阈值
        Scalar lowerBound = new Scalar(31, 27, 153); // 黄色
        Scalar upperBound = new Scalar(41, 37, 255);

        // 创建掩码
        Mat mask = new Mat();
        Core.inRange(hsv, lowerBound, upperBound, mask);

        // 形态学操作
        Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
        Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_OPEN, kernel);

        // 查找轮廓
        List<MatOfPoint> contours = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(mask, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

        // 在原图上绘制检测到的目标
        Mat result = image.clone();
//        Mat result = hierarchy.clone();
        for (MatOfPoint contour : contours) {
            // 计算轮廓的面积
            double area = Imgproc.contourArea(contour);

            // 筛选面积较大的轮廓
            if (area > 1) {
                // 寻找包围矩形
                Rect rect = Imgproc.boundingRect(contour);

                // 绘制轮廓或包围矩形
                Imgproc.rectangle(result, rect.tl(), rect.br(), new Scalar(0, 0, 255), 2);
            }
        }

        // 显示结果
//        Imgcodecs.imwrite("result.jpg", result);
        HighGui.imshow("模板匹配", result);
        HighGui.waitKey();
    }
}